package test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger; // 修复：导入AtomicInteger

// 1. 定义顾客类
class Customer {
    private String name;

    public Customer(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

// 2. 定义优惠券类（共享资源）
class Coupon {
    private final AtomicInteger remaining;

    public Coupon(int total) {
        this.remaining = new AtomicInteger(total);
    }

    // 尝试抢购优惠券（原子操作）
    public boolean trySeize() {
        while (true) {
            int current = remaining.get();
            if (current <= 0) return false;
            // 使用CAS操作保证原子性
            if (remaining.compareAndSet(current, current - 1)) {
                return true;
            }
        }
    }

    public int getRemaining() {
        return remaining.get();
    }
}

// 3. 定义抢购任务（实现Callable）
class CouponTask implements Callable<Boolean> {
    private final Customer customer;
    private final Coupon coupon;

    public CouponTask(Customer customer, Coupon coupon) {
        this.customer = customer;
        this.coupon = coupon;
    }

    @Override
    public Boolean call() {
        synchronized (this) {
            // 模拟网络延迟
            try {
                Thread.sleep((long) (Math.random() * 100));
            } catch (InterruptedException e) {
                return false;
            }
        }

        boolean success = coupon.trySeize();
        System.out.printf("%s 抢购%s%n",
                customer.getName(),
                success ? "成功！剩余：" + coupon.getRemaining() : "失败！优惠券已抢完");
        return success;
    }
}

public class CouponSeckill {
    public static void main(String[] args) {
        final int TOTAL_COUPONS = 10;  // 优惠券总数
        final int MAX_CUSTOMERS = 50;  // 最大顾客数

        // 创建共享优惠券资源
        Coupon coupon = new Coupon(TOTAL_COUPONS);

        // 创建线程池（核心线程数=CPU核心数*2，最大线程数=核心线程数*3）
        ExecutorService pool = Executors.newFixedThreadPool(
                Runtime.getRuntime().availableProcessors() * 2);

        List<Future<Boolean>> futures = new ArrayList<>();
        int successCount = 0;

        // 模拟多个顾客同时抢购
        for (int i = 1; i <= MAX_CUSTOMERS; i++) {
            Customer customer = new Customer("顾客" + i);
            Future<Boolean> future = pool.submit(new CouponTask(customer, coupon));
            futures.add(future);

            // 实时检查抢购结果
            try {
                if (future.get()) {  // 如果抢购成功
                    successCount++;
                }
                // 不再提前终止任务提交，让所有顾客都有机会尝试
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        // 关闭线程池并等待所有任务完成
        pool.shutdown();
        try {
            pool.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 统计最终结果
        System.out.println("\n===== 抢购结果统计 =====");
        System.out.println("总优惠券数量: " + TOTAL_COUPONS);
        System.out.println("成功抢购人数: " + successCount);
        System.out.println("剩余优惠券数量: " + coupon.getRemaining());
        System.out.println("实际参与人数: " + futures.size());
    }
}
